﻿using AutoMapper;
using BPMN.Application.Contracts.DTO.Request.UserInfo;
using BPMN.Application.Contracts.DTO.Response;
using BPMN.Application.Contracts.DTO.Response.Role;
using BPMN.Application.Contracts.DTO.Response.RolePermission;
using BPMN.Application.Contracts.DTO.Response.UserInfo;
using BPMN.Application.IService;
using BPMN.Domain.Entity.User;
using BPMN.DomianShare;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration.UserSecrets;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OfficeOpenXml;
using Org.BouncyCastle.Asn1.X9;
using System.Data;
using Xceed.Wpf.Toolkit;
using Yitter.IdGenerator;

namespace BPMN.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize]
    public class UserController : ControllerBase
    {
        private readonly IUserAppService AppUser;

        public UserController(IUserAppService AppUser)
        {
            this.AppUser = AppUser;
        }
        /// <summary>
        /// 测试接口GET
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Test()
        {
            int a = 0;
            int b = 0;
            return Ok(a / b);
        }

        /// <summary>
        /// 显示全部
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserInfo()
        {
            return Ok(await AppUser.GetUserInfo());
        }
        /// <summary>
        /// 根据Id获取用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserInfoById(int Id)
        {
            return Ok(await AppUser.GetUserInfoById(Id));
        }
        /// <summary>
        /// 删除功能
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleteUserInfo(int Id)
        {
            return Ok(await AppUser.Delete(Id));
        }
        /// <summary>
        ///  用户添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddUserInfo(UserInfoRequestDto entity)
        {
            return Ok(await AppUser.AddUserInfo(entity));
        }
        /// <summary>
        /// 修改功能
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateUserInfo(UserInfoRequestDto entity)
        {
            return Ok(await AppUser.UpdateUserInfo(entity));
        }
        /// <summary>
        /// 用户删除功能
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleleUserInfo(int UserId)
        {
            return Ok(await AppUser.DeleleUserInfo(UserId));

        }
        /// <summary>
        /// 登录功能
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Pwd"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> LoginAction(string UserName, string Pwd)
        {
            return Ok(await AppUser.LoginAction(UserName, Pwd));
        }
        /// <summary>
        /// 菜单列表显示
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> PermissionListShow(int UserId)
        {
            //中午去吃烤肉拌饭15一份好吃实惠
            return Ok(await AppUser.PermissionListShow(UserId));
        }
        [HttpGet]
        public async Task<IActionResult> GetRolePeimiss(int UserId, int? PermId)
        {
            return Ok(await AppUser.GetRolePeimiss(UserId,PermId));
        }

        /// <summary>
        /// Excel导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetExcel()
        {
            var stdList = (await AppUser.GetUserInfo()).Data;
            //string exceiFile = Application.StartupPath + "\\StudentInfo.xls";
            ExcelHelper<UserInfoShowResponseDto>.SaveExcelFile(PathHelper.GetSecretsPathFromSecretsId + "用户.xls", "Student", stdList);
            //ExcelHelper<UserInfoShowResponseDto>.SaveExcelFile(exceiFile, "Student", stdList);
            return Ok(1);
        }
        /// <summary>
        /// 批量添加用户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> RuolUserAdd(List<UserInfoRequestDto> dto)
        {
            return Ok(await AppUser.RuolUserAdd(dto));
        }
        /// <summary>
        /// 导入Excel文件
        /// </summary>
        /// <param name="excelFile"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> UploadUserInfo(IFormFile excelFile)
        {
            try
            {
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(new
                    {
                        error = 1,
                        msg = "必须是Excel文件"
                    });
                }

                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }
                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;

                List<UserInfoRequestDto> stuList = new();
                for (int i = 1; i <= totalRow; i++)
                {

                    IRow row = sheet.GetRow(i);
                    // 判定第5列的值是不是日期，日期的值类型可以按日期来读，也可以用数据的方式来读
                    //var isDate = DateUtil.IsCellDateFormatted(row.GetCell(4));

                    string UserName = row.GetCell(1).StringCellValue;
                    string Name = row.GetCell(2).StringCellValue;
                    string Tel = row.GetCell(3).StringCellValue;
                    string Email = row.GetCell(4).StringCellValue;

                    //// 第6列有可能是空的
                    //string Pic = "";
                    //if (row.GetCell(6) != null)
                    //{
                    //    CellType type = row.GetCell(6).CellType;
                    //    if (type != CellType.Blank)
                    //    {
                    //        Pic = row.GetCell(6).StringCellValue;
                    //    }
                    //}

                    //int State = (int)row.GetCell(7).NumericCellValue;

                    var stu = new UserInfoRequestDto
                    {
                        UserName = UserName,
                        Name = Name,
                        Tel = Tel,
                        Email = Email
                    };
                    stuList.Add(stu);
                }
                   await AppUser.RuolUserAdd(stuList);
                wb.Close();
                return Ok(1);
            }
            catch (Exception)
            {
                throw;
            }
        }


        #region 控制器代码

        /// <summary>
        /// 现实是所有扩展的字段
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetExtend()
        {
            try
            {
                return Ok(await AppUser.GetExtend());
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 添加扩展字段
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddExtend(Extend Data)
        {
            try
            {
                return Ok(AppUser.AddExtend(Data));
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除扩展字段
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DelExtend(int id)
        {
            try
            {
                return Ok(AppUser.DelExtend(id));
            }
            catch (Exception)
            {

                throw;
            }
        }

        [HttpGet]
        public async Task<IActionResult> ShowUserInfoAndExtendId()
        {
            try
            {
                //所有用户信息
                return Ok(await AppUser.ShowUserInfoAndExtendId());
            }
            catch (Exception)
            {

                throw;
            }
        }
        [HttpGet]
        public async Task<IActionResult> GetExtendById()
        {
            try
            {
                return Ok(await AppUser.GetExtendById());
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 添加自定义扩展字段
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddUserInfoAndExtendId(AddUserDto Dto)
        {
            try
            {
                //所有用户信息
                return Ok(await AppUser.AddUserInfoAndExtendId(Dto));
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 自定义扩展修改功能
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdUserInfoAndExtendId(AddUserDto entity)
        {
            try
            {
                return Ok(await AppUser.UpdUserInfoAndExtendId(entity));

            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 根据Id获取用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserInfoByIds(int Id)
        {
            return Ok(await AppUser.GetUserInfoByIds(Id));
        }
        #endregion
    }
}
